package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author wzh
 * @create 2022/5/27 9:45
 * @Description：第一个拦截器用于持续刷新token，需要拦截所有请求
 */

public class RefershTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    public RefershTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//       获取请求头中的token
        String token = request.getHeader("authorization");
//        判断用户是否存在
        //   不存在则对该线程进行放行进入到第二个拦截器，即为登录
        if (StrUtil.isBlank(token)){
            return true;
        }
//        已登录
        String key=RedisConstants.LOGIN_USER_KEY + token;
//        基于token获取用户的信息，为了将用户的信息存放在ThreadLocal之中
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
        if (entries.isEmpty()){
            response.setStatus(401);
            return false;
        }
//        将查询到的hash数据转化为UserDTO对象 false不忽视，即如果转化错误则抛出异常
        UserDTO user = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);

//        存在则保存用户到ThreadLocal中
        UserHolder.saveUser(user);
//        刷新token的有效期
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
//        放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
